<?php

/**
* alltosun.com  express_helper.php for newbd
* ============================================================================
* 版权所有 (C) 2009-2014 北京互动阳光科技有限公司，并保留所有权利。
* 网站地址: http://www.alltosun.com
* ----------------------------------------------------------------------------
* 许可声明: 这是一个开源程序，未经许可不得将本软件的整体或任何部分用于商业用途及再发布。
* ============================================================================
* Author: 吴松键 (wusj@alltosun.com)
* Date: 15/2/4 下午2:51
*/

class express_helper
{
    /**
     * 通过relation_id 获取地址列表
     */
    public static function get_provincial_list($relation_id)
    {
        if (!$relation_id) {
            return array();
        }

        $provincial_ids = _model('provincial_relation')->getFields('provincial_id', array('express_relation_id'=>$relation_id));

        if (!$provincial_ids) {
            return array();
        }

        $list = _model('provincial')->getList(array('id'=>$provincial_ids));

        return $list;
    }

    /**
     * 通过relation_id 获取地址标题集合
     */
    public static function get_provincial_title($relation_id)
    {
        $list = self::get_provincial_list($relation_id);
        if (!$list) {
            return '';
        }

        $title = array();
        foreach ($list as $k=>$v) {
            $title[] = $v['title'];
        }

        return join(',', $title);
    }

    /**
     * 根据订单去快递价格
     */
    public static function get_express_price_by_order($order_id, $express_id, $address_id, $prov = '', $city = '', $dist = '')
    {
        if (!$order_id) {
            return array('info'=>'请选择需要查看的订单');
        }
        if (!$express_id) {
            return array('info'=>'请选择运送方式');
        }
        if (!$address_id && !($prov || $city || $dist)) {
            return array('info'=>'请选择运送地址');
        }

        if (!$address_id) {
            $address_ids = provincial_helper::get_id_by_title($prov, $city, $dist);
        } else {
            $address_info = _uri('address', $address_id);
            $address_ids = array(
                'prov_id' => $address_info['province_id'],
                'city_id' => $address_info['city_id'],
                'dist_id' => $address_info['district_id']
            );
        }

        $provincial_relation_ids = '';
        $filter['express_id'] = $express_id;
//         $filter['status'] = 1;
        if (!$provincial_relation_ids && isset($address_ids['dist_id']) && $address_ids['dist_id']) {
            $filter['provincial_id'] = $address_ids['dist_id'];
            $provincial_relation_ids = _model('provincial_relation')->getFields('express_relation_id', $filter);
        }
        if (!$provincial_relation_ids && isset($address_ids['city_id']) && $address_ids['city_id']) {
            $filter['provincial_id'] = $address_ids['city_id'];
            $provincial_relation_ids = _model('provincial_relation')->getFields('express_relation_id', $filter);
        }
        if (!$provincial_relation_ids && isset($address_ids['prov_id']) && $address_ids['prov_id']) {
            $filter['provincial_id'] = $address_ids['prov_id'];
            $provincial_relation_ids = _model('provincial_relation')->getFields('express_relation_id', $filter);
        }

        $express_price = 0;
        if ($provincial_relation_ids) {
            $express_relation_info = _model('express_relation')->read(array('id'=>$provincial_relation_ids, 'status'=>1));
            if (!$express_relation_info) {
                return array('info'=>'当前地址不在运送范围内');
            }

            // 如果价格达到免费额度,直接免运费
            $order_info = _uri('order', $order_id);
            if ($order_info['price']+$order_info['promotion_price']-$order_info['post_price'] >= $express_relation_info['free_price']) {
                return array('info'=>'ok', 'price'=>0);
            }

            $order_relation_list = _model('order_relation')->getList(array('order_id'=>$order_id));
            if ($order_relation_list && $express_relation_info['type'] == 2) {
                foreach ($order_relation_list as $k=>$v) {
                    $goods_info = _uri('goods', $v['goods_id']);
                    if ($goods_info['free_express'] == 0) {
                        $express_price += $express_relation_info['price']*$v['goods_num'];
                    }
                }
            } elseif ($order_relation_list && $express_relation_info['type'] == 1) {
                $weight = 0;
                foreach ($order_relation_list as $k=>$v) {
                    $goods_info = _uri('goods', $v['goods_id']);
                    $weight += $v['goods_num']*$goods_info['goods_weight'];
                }
                if ($weight < 1000) {
                    $express_price = $express_relation_info['price'];
                } else {
                    $renew_weight = ceil($weight/1000)-1;
                    $express_price = $express_relation_info['price']+$renew_weight*$express_relation_info['renew_price'];
                }
            } else {
                return array('info'=>'请选择正确的快递公司');
            }
        } else {
            return array('info'=>'您的收货地址不在配送范围');
        }

        return array('info'=>'ok', 'price'=>$express_price);
    }

    /**
     * 通过地址信息获取快递价格
     */
    public static function get_express_price($express_id, $address_id)
    {
        if (!$express_id) {
            return array('info'=>'请选择运送方式');
        }
        if (!$address_id) {
            return array('info'=>'请选择运送地址');
        }

        $address_info = _uri('address', $address_id);
        $provincial_relation_ids = '';
        $filter['express_id'] = $express_id;
        if (!$provincial_relation_ids && $address_info['district_id']) {
            $filter['provincial_id'] = $address_info['district_id'];
            $provincial_relation_ids = _model('provincial_relation')->getFields('express_relation_id', $filter);
        }
        if (!$provincial_relation_ids && $address_info['city_id']) {
            $filter['provincial_id'] = $address_info['city_id'];
            $provincial_relation_ids = _model('provincial_relation')->getFields('express_relation_id', $filter);
        }
        if (!$provincial_relation_ids && $address_info['province_id']) {
            $filter['provincial_id'] = $address_info['province_id'];
            $provincial_relation_ids = _model('provincial_relation')->getFields('express_relation_id', $filter);
        }

        $express_price = 0;
        if ($provincial_relation_ids) {
            $express_relation_info = _model('express_relation')->read(array('id'=>$provincial_relation_ids, 'status'=>1));
            if (!$express_relation_info) {
                return array('info'=>'您的收货地址不在配送范围');
            }

            // 如果价格达到免费额度,直接免运费
            $cart_total = cart_helper::get_cart_price_total(false);
            if ($cart_total >= $express_relation_info['free_price']) {
                return array('info'=>'ok', 'price'=>0);
            }

            $cart_list = cart_helper::cart_merge();
            if ($cart_list && $express_relation_info['type'] == 2) {
                foreach ($cart_list as $k=>$v) {
                    $goods_info = _uri('goods', $v['goods_id']);
                    if ($goods_info['free_express'] == 0) {
                        $express_price += $express_relation_info['price']*$v['goods_num'];
                    }
                }
            } elseif ($cart_list && $express_relation_info['type'] == 1) {
                $weight = 0;
                foreach ($cart_list as $k=>$v) {
                    $goods_info = _uri('goods', $v['goods_id']);
                    if ($goods_info['free_express'] == 0) {
                        $weight += $v['goods_num']*$goods_info['goods_weight'];
                    }
                }
                if ($weight < 1000) {
                    $express_price = $express_relation_info['price'];
                } else {
                    $renew_weight = ceil($weight/1000)-1;
                    $express_price = $express_relation_info['price']+$renew_weight*$express_relation_info['renew_price'];
                }
            } else {
                return array('info'=>'请选择正确的快递公司');
            }
        } else {
            return array('info'=>'您的收货地址不在配送范围');
        }

        return array('info'=>'ok', 'price'=>$express_price);
    }

    /**
     * 快递100快递查询
     * @param  [type] $express_code [快递公司代码]
     * @param  [type] $express_no   快递单号
     * @return [type]               快递信息
     */
    public static function get_express_info($express_code, $express_no)
    {
        if (!$express_code || !$express_no) {
            return '';
        }

        $param = array(
                'id' => express_config::$express_key,
                'com' => $express_code,
                'nu'  => $express_no,
                'valicode' => '',
                'show' => 0,
                'muti' => 1,
                'order' => 'asc'
            );

        $url = 'http://api.kuaidi100.com/api?'.http_build_query($param);

        return an_curl($url);
    }

    /**
     * 通过订单id获取快递信息
     * 
     * @param  [type] $order_id [description]
     * @return [type]           [description]
     */
    public static function express_info_by_order($order_id, $order = 'asc')
    {
        if (!$order_id) {
            return array('info'=>'请选择需要查看的快递号');
        }

        $order_info = _uri('order', $order_id);
        $user_id = user_helper::get_user_id();
        if($order_info['user_id'] != $user_id) {
            return array('info'=>'此订单不存在');
        }
        if ($order_info['progress'] < 15 || !$order_info['express_no']) {
            return array('info'=>'当前订单还未发货，请稍后查询');
        }
        $express_no = $order_info['express_no'];
        if (!$express_no) {
            return array('当前订单暂未发货');
        }

        $express_code = _uri('express', $order_info['express_id'], 'express_code');

        //$express_code = 'yuantong';
        //$express_no   = '880047680996640772';
        $info = self::express_info($express_code, $express_no, $order);
        if ($info) {
            $info = json_decode($info, true);
            if (($info['status'] == 3 || $info['status'] == 4) && $order_info['express_receiver_time'] == '0000-00-00 00:00:00') {
                _model('order')->update(array('id'=>$order_id), array('express_receiver_time'=>date('Y-m-d H:i:s', $info['update'])));
            }
            if ($info['status'] == 0) {
                return array('info'=>$info['message']);
            }

            return array('info'=>'ok', 'json'=>$info);
        }

        return array('info'=>'查询失败，请重试');
    }

    /**
     * 根据快递号，快递公司，查询快递信息
     */
    public static function express_info($express_code, $express_no, $order = 'asc')
    {
        if (!$express_code || !$express_no) {
            return '';
        }

        $param = array(
                'id' => express_config::$express_ickd['id'],
                'secret' => express_config::$express_ickd['key'],
                'com' => $express_code,
                'nu'  => $express_no,
                'type' => 'json',
                'encode' => 'utf8',
                'ord' => $order
            );

        $url = 'http://api.ickd.cn/';
        //$url = 'http://api.ickd.cn/?'.http_build_query($param);

        return an_curl($url, $param);
    }
}